package com.hn.gege.sys.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hn.gege.sys.modules.sys.entity.User;
import com.hn.gege.sys.modules.sys.service.IUserRoleService;
import com.hn.gege.sys.modules.sys.mapper.UserMapper;
import com.hn.gege.sys.modules.sys.service.IUserService;
import com.hn.gege.core.common.MyException;
import com.hn.gege.core.common.ParmException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author zxy
 * @since 2020-08-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Value("${project.default.pwd}")
    private String pwd;
    @Value("${project.rolecode.default}")
    private String defaultRole;

    @Autowired
    IUserRoleService userRoleService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public boolean add(User user) throws ParmException {
        //校验用户,如果临时登录过,返回id
        String userId = this.checkUser(user.getPhone(), user.getEmall(), user.getIdno());

        if (StringUtils.isEmpty(user.getPassword()))
            user.setPassword(passwordEncoder.encode(pwd));
        else
            user.setPassword(passwordEncoder.encode(user.getPassword()));

        boolean b = false;
        //如果用户注册前没有用邮箱登录过,直接新增,否则在原有数据上修改
        if (userId == null){
            b = super.save(user);
        }else {
            user.setId(userId);
            b = super.updateById(user);
        }
        //设置默认角色
        userRoleService.setDefaultRole(user.getId(), defaultRole);
        return b;
    }

    @Override
    public boolean updatePwd(String id, String oldpwd, String newpwd) throws MyException {
        User user = super.getById(id);
        if (user == null)
            throw new MyException("id有误");

        boolean matches = passwordEncoder.matches(oldpwd, user.getPassword());
        if (!matches)
            throw new MyException("旧密码错误");

        String password = passwordEncoder.encode(newpwd);
        LambdaUpdateWrapper<User> updateWrapper = new UpdateWrapper<User>().lambda()
                .set(User::getPassword, password)
                .eq(User::getId, id);
        return super.update(updateWrapper);

    }

    @Override
    public User getByPk(String id) {
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda()
                .eq(User::getId, id);
        return baseMapper.selectOne(lambda);
    }

    @Override
    public boolean updateByPk(User user) {
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda()
                .eq(User::getId, user.getId());
        return super.update(user, lambda);
    }

    @Override
    public boolean removeByPk(String id) {
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda()
                .eq(User::getId, id);
        return super.remove(lambda);
    }

    @Override
    public User getByUserName(String userName) {
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda()
                .eq(User::getPhone, userName)
                .or().eq(User::getIdno, userName)
                .or().eq(User::getEmall, userName);
        return super.getOne(lambda);
    }

    @Override
    public String checkUser(String phone, String email, String idno) throws ParmException {

        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(idno) && StringUtils.isEmpty(email))
            throw new ParmException("手机号/身份证号/邮件不可同时为空");

        User user = null;
        if ( ! StringUtils.isEmpty(phone)) {
            user = this.getByUserName(phone);
            if (user != null)
                throw new ParmException("手机号已被注册");
        }

        if ( ! StringUtils.isEmpty(idno)) {
            user = this.getByUserName(idno);
            if (user != null)
                throw new ParmException("身份证号已被注册");
        }

        if ( ! StringUtils.isEmpty(email)) {
            user = this.getByUserName(email);
            if (user != null){
                //密码等null,表示该邮箱有临时登录的记录,并没有被注册
                if (user.getPassword() == null){
                    return user.getId();
                }else{
                    throw new ParmException("邮箱已被注册");
                }
            }
        }
        return null;
    }


}
